<?php

require_once('conf/DBConnection.php');
require_once('dao/DAO.php');

class ViajesDAO extends DAO {

	function ViajesDAO() {}

	function get($id){
		DBConnection::getInstance();
		$query = "SELECT * FROM viajes WHERE id = $id";
		$result = mysql_query($query);
		$results = $this->getFromResult($result);
		return $results[0];
	}

	function find($criteria){
		DBConnection::getInstance();
		$conditions = $this->getConditions($criteria);
		$query = "SELECT *,V.id as idViaje, C1.ciudad as ciudadOrigen, C2.ciudad as ciudadDestino FROM viajes as V ". 
				 "INNER JOIN transportes as T ON T.id = V.idTransporte ".
				 "INNER JOIN ciudades as C1 ON C1.id = V.origen ".
				 "INNER JOIN ciudades as C2 ON C2.id = V.destino ".
				 "WHERE 1=1 $conditions";
		//echo $query;
		$result = mysql_query($query);
		return $this->getFromResult($result);
	}

	function deleteFisico($id){
		DBConnection::getInstance();
		$query = "DELETE FROM viajes WHERE id = $id";
		$result = mysql_query($query);
		return parent::checkError($result);
	}

	function delete($id){
		DBConnection::getInstance();
		$query = "UPDATE viajes SET borrado = '1' WHERE id = $id";
		$result = mysql_query($query);
		return parent::checkError($result);
	}

	function insert($vo) {
		DBConnection::getInstance();
		$query = "INSERT INTO viajes(id, fecha, origen, destino, idTransporte, tipoCamion, descripcion, borrado) VALUES
				(NULL, '".$vo->getFecha()."', '".$vo->getOrigen()."', '".$vo->getDestino()."', '".$vo->getIdTransporte()."', '".$vo->getTipoCamion()."', '".$vo->getDescripcion()."', '".$vo->getBorrado()."')";
		$result = mysql_query($query);
		return parent::checkError($result);
	}

	function update($vo) {
		DBConnection::getInstance();
		$query = "UPDATE viajes SET ".
				"fecha ='".$vo->getFecha()."', ".
				"origen ='".$vo->getOrigen()."', ".
				"destino ='".$vo->getDestino()."', ".
				"idTransporte ='".$vo->getIdTransporte()."', ".
				"tipoCamion ='".$vo->getTipoCamion()."', ".
				"descripcion ='".$vo->getDescripcion()."' ".
				" WHERE id =".$vo->getId();
		echo $query;
		$result = mysql_query($query);
		return parent::checkError($result);
	}

	function getConditions($criteria){
		if ($criteria->getFecha() != null) {
			$conditions.= " AND fecha= '".$criteria->getFecha()."'";
		}
		if ($criteria->getOrigen() != null) {
			$conditions.= " AND origen= '".$criteria->getOrigen()."'";
		}
		if ($criteria->getDestino() != null) {
			$conditions.= " AND destino= '".$criteria->getDestino()."'";
		}
		if ($criteria->getIdTransporte() != null) {
			$conditions.= " AND idTransporte= '".$criteria->getIdTransporte()."'";
		}
		if ($criteria->getTipoCamion() != null) {
			$conditions.= " AND tipoCamion= '".$criteria->getTipoCamion()."'";
		}

		$conditions .= parent::getConditionsAbs($criteria,'V');
		return $conditions;
	}

}

